package utils.reader.support;

import java.io.IOException;
import java.io.InputStream;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.xml.sax.EntityResolver;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import utils.path.support.ClassConfigPath;
import utils.resource.support.XMLDocumentResource;
import utils.test.Assert;

/**
 * XML文档资源读取器
 * @author Administrator
 *
 */
public class XMLDocumentResourceReader extends AbstractResourceReader{
	
	private static final String BEAN_DOC_VLD = "bean-doc-vld.dtd";

	@Override
	public void packageResource(String path) {
		Assert.isNotNull(this.inputStream, "Stream is Null，do Read Method First.");
		Document doc = parseDocument(this.inputStream,path);
		this.resource = new XMLDocumentResource(doc,path);
	}
	
	/**
	 * 解决DTD 
	 * publicId,systemId问题
	 * @author Administrator
	 *
	 */
	private class CustomEntityResolver implements EntityResolver{
		public InputSource resolveEntity(String publicId, String systemId)
				throws SAXException, IOException {
			ClassConfigPath path = new ClassConfigPath(BEAN_DOC_VLD);
			String systemIdLocation = path.getLocation()[0];
			return new InputSource(systemIdLocation);
		}
	}
	
	/**
	 * 输入流，转换成文档
	 * @param in 文档输入流
	 * @param systemId 
	 * @return
	 */
	private Document parseDocument(InputStream in,String systemId){
		try{
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			DocumentBuilder dbd = dbf.newDocumentBuilder();
			dbd.setEntityResolver(new CustomEntityResolver());
			Document doc = dbd.parse(in);
	        return doc;
		}catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
}
